package com.qf.servlet;

import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class Demo2Servlet extends HttpServlet {
    private UserService userService=new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //0
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //1
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2数据传给业务层
        User user = userService.login(username, password);
        //3作出响应
        PrintWriter writer = resp.getWriter();
        if (user != null) {// 说明登录成功
            writer.write("<html>");
            writer.write("<head>");
            writer.write("<title>登录成功</title>");
            writer.write("</head>");
            writer.write("<body>");
            writer.write("<h1>欢迎 [ "+user.getUsername()+" ]</h1>");
            writer.write("<hr>");
            writer.write("<h3>个人信息如下:</h3>");
            writer.write("<table border='2'>");
            writer.write("<thead>");
            writer.write("<td>编号</td>");
            writer.write("<td>用户名</td>");
            writer.write("<td>密码</td>");
            writer.write("<td>手机号</td>");
            writer.write("<td>注册时间</td>");
            writer.write("<td>余额</td>");
            writer.write("<td>性别</td>");
            writer.write("</thead>");
            writer.write("<tr>");
            writer.write("<td>"+user.getId()+"</td>");
            writer.write("<td>"+user.getUsername()+"</td>");
            writer.write("<td>"+user.getPassword()+"</td>");
            writer.write("<td>"+user.getPhone()+"</td>");
            writer.write("<td>"+user.getCreateTime()+"</td>");
            writer.write("<td>"+user.getMoney()+"</td>");
            writer.write("<td>"+(user.getSex() == 1 ? "男":"女")+"</td>");
            writer.write("</tr>");
            writer.write("</table>");
            writer.write("</body>");
            writer.write("</html>");
        } else {
            writer.write("<html>");
            writer.write("<head>");
            writer.write("<title>登录失败</title>");
            writer.write("</head>");
            writer.write("<body>");
            writer.write("<h1 style='color:red'>用户名或密码错误</h1>");
            writer.write("</body>");
            writer.write("</html>");
        }
    }
}
